package swing.frame;

import api.MainServer;
import beans.Group;
import beans.User;
import beans.Whiteboard;
import client.UserSession;
import com.syuchen.protocol.http.Response;
import model.ApiResultModel;
import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper;
import swing.BaseFrame;
import swing.FrameManager;
import swing.customComp.*;
import swing.dialog.AddGroupDialog;
import swing.dialog.AddMemberDialog;
import swing.dialog.AddWhiteboardDialog;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;


class MyJList extends JList{
    @Override
    public int locationToIndex(Point location) {
        int index = super.locationToIndex(location);
        if (index == this.getModel().getSize() - 1) {
            Rectangle rectangle = getCellBounds(index, index);
            if (rectangle == null || !rectangle.contains(location))
                return -1;
        }
        return index;
    }
}


public class MainFrame extends BaseFrame
{
    JTextField  searchGroup;
    JButton     newGroup;
    JList       groupList;

    JLabel      groupLabel;



    JList       whiteboardList;
    JButton add_whiteboard;


    JLabel      adminLabel;
    JButton     addMember;
    JList       memberList;
    String[]    memberData;

    JButton     dismiss;    // 管理员解散
    JButton     exit;       // 普通成员退出


    Box leftFrame;
    Box middleFrame;
    Box rightFrame;

    public void clearGroupSelection(){
        UserSession.clearGroupSelection();
        groupList.clearSelection();
    }

    public void clearWhiteboardSelection(){
        UserSession.clearWhiteboardSelection();
        whiteboardList.clearSelection();
    }

    public void clearMemberSelection(){
        UserSession.clearMemberSelection();
        memberList.clearSelection();
    }

    public void updateWhiteboardList(){
        boolean isGroupSelectionValid = UserSession.isGroupSelectionValid();
        groupLabel.setVisible(isGroupSelectionValid);
        add_whiteboard.setVisible(isGroupSelectionValid);
        if (!isGroupSelectionValid){
            whiteboardList.setListData(new Object[0]);
            return;
        }
        String group_name = String.format("%s (%d)", UserSession.getSelectedGroup().getGroup_name(), UserSession.getGroupMemberAmount());
        groupLabel.setText(group_name);
        boolean isAddWhiteboardVisible = UserSession.getSelectedGroup().getAdmin_id() == UserSession.user.getId();
        add_whiteboard.setVisible(isAddWhiteboardVisible);


        try {
            Group group = UserSession.getSelectedGroup();
            String group_id = Long.toString(group.getId());

            Response response = MainServer.groupAction.get_whiteboard_list(Long.parseLong(group_id));
            ApiResultModel<List<Whiteboard>> apiResult = ApiResultModel.parseAndCheckResponse(response, this, Whiteboard.class, true);

            UserSession.setWhiteboardList(apiResult.getResult());
            String whiteboard_name_list[] = UserSession.getWhiteboardNameList();
            whiteboardList.setListData(whiteboard_name_list);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    public void updateGroupList() {
        try {
            Response response = MainServer.groupAction.get_group_list(UserSession.user.getId());
            ApiResultModel<List<Group>> apiResult = ApiResultModel.parseAndCheckResponse(response, this, Group.class, true);
            List<Group> group_list_data = apiResult.getResult();
            UserSession.setGroupList(group_list_data);
            String group_name_list[] = UserSession.getGroupNameList();
            groupList.setListData(group_name_list);
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }

    public void updateMemberList(){
        // 如果没有选择组，则标签和添加白板两项不可见
        boolean isGroupSelectionValid = UserSession.isGroupSelectionValid();
        adminLabel.setVisible(isGroupSelectionValid);
        addMember.setVisible(isGroupSelectionValid);
        if (!isGroupSelectionValid) {
            exit.setVisible(false);
            dismiss.setVisible(false);
            memberList.setListData(new Object[0]);
            return;
        }


        boolean isGroupAdmin = UserSession.getSelectedGroup().getAdmin_id() == UserSession.user.getId();
        addMember.setVisible(isGroupAdmin);
        exit.setVisible(!isGroupAdmin);
        dismiss.setVisible(isGroupAdmin);


        try {
            Response response = MainServer.userAction.query_user_name(UserSession.getSelectedGroup().getAdmin_id());
            String admin_name = (String) (ApiResultModel.parseAndCheckResponse(response, this, String.class, false).getResult());
            adminLabel.setText("管理员：" + admin_name);


            long group_id = UserSession.getSelectedGroup().getId();
            response = MainServer.groupAction.get_member_list(group_id);
            ApiResultModel<List<User>> apiResult = ApiResultModel.parseAndCheckResponse(response, this, User.class, true);
            UserSession.setMemberList(apiResult.getResult());
            String member_name_list[] = UserSession.getMemberNameList();
            memberList.setListData(member_name_list);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
    Box initLeft(){
        Box box = Box.createVerticalBox();
        searchGroup = new JTextField();
        searchGroup.setMaximumSize(new Dimension(220, 40));
        searchGroup.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 监听到回车了
                String keyWord = searchGroup.getText().trim();

                if (keyWord.length() == 0)
                    UserSession.cancelGroupFilter();
                else
                    UserSession.setGroupFilterWord(keyWord);

                updateGroupList();
                groupList.setSelectedIndex(0);
                UserSession.setSelectedGroupIndex(0);

                updateMemberList();
                updateWhiteboardList();

            }
        });


        newGroup = new JButton("+");
        newGroup.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 单击事件
                AddGroupDialog addGroupDialog = new AddGroupDialog(MainFrame.this);
                addGroupDialog.setVisible(true);
            }
        });

        Box search_add = Box.createHorizontalBox();
        search_add.add(searchGroup);
        search_add.add(Box.createHorizontalStrut(5));
        search_add.add(newGroup);
        search_add.setMinimumSize(new Dimension(260,100));
        search_add.setMaximumSize(new Dimension(260,100));
//        search_add.setAlignmentX(Component.RIGHT_ALIGNMENT);
        search_add.setBorder(new EmptyBorder(8, 3, 10, 3));    //设置面板的边框
        box.add(search_add);

        JPopupMenu groupMenu = new JPopupMenu();
        JMenuItem refreshGroup = new JMenuItem("刷新群组列表");
        refreshGroup.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateGroupList();
                groupList.setSelectedIndex(0);
                UserSession.setSelectedGroupIndex(0);

                updateMemberList();
                updateWhiteboardList();

            }
        });
        groupMenu.add(refreshGroup);

        JScrollPane scrollPane=new JScrollPane();    //创建滚动面板
        groupList=new MyJList();
        groupList.setFixedCellHeight(50);
        groupList.setFont(new Font("微软雅黑", Font.TRUETYPE_FONT, 16));

        GroupListMouseListener groupListMouseListener = new GroupListMouseListener(groupList, groupMenu);
        groupList.addMouseListener(groupListMouseListener);
        //限制只能选择一个元素
        groupList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        groupList.setCellRenderer(new GroupListCellRenderer());
        scrollPane.setViewportView(groupList);    //在滚动面板中显示列表
        box.add(scrollPane);
        box.setPreferredSize(new Dimension(260,640 ));
        return box;
    }

    Box initCenter(){
        Box box = Box.createVerticalBox();
        Box group_add = Box.createHorizontalBox();
        add_whiteboard = new JButton("+");
        add_whiteboard.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 单击事件
                AddWhiteboardDialog addWhiteboardDialog = new AddWhiteboardDialog(MainFrame.this);
                addWhiteboardDialog.setVisible(true);
            }
        });
        groupLabel = new JLabel();
        groupLabel.setFont(new Font("微软雅黑", Font.TRUETYPE_FONT, 24));
        group_add.add(Box.createVerticalStrut(30));
        group_add.add(groupLabel);
        group_add.add(Box.createVerticalStrut(30));
        group_add.add(add_whiteboard);
        group_add.setBorder(new EmptyBorder(8, 5, 8, 5));    //设置面板的边框
        box.add(group_add);


        JPopupMenu whiteboardMenu = new JPopupMenu();
        JMenuItem openWhiteboard = new JMenuItem("打开");
        JMenuItem removeWhiteboard = new JMenuItem("删除");
        JMenuItem refreshWhiteboard = new JMenuItem("刷新白板列表");
        openWhiteboard.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                boolean isAdmin = UserSession.getSelectedGroup().getAdmin_id() == UserSession.user.getId();
                String groupName=UserSession.getSelectedGroup().getGroup_name();
                FrameManager.showWhiteBoard(UserSession.getSelectedWhiteboard(), isAdmin,groupName);
            }
        });

        removeWhiteboard.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int option = JOptionPane.showConfirmDialog(box,"确定要删除吗？","删除提示",JOptionPane.YES_NO_OPTION);
                if (option == 1)
                    return;
                // 如果点了确定返回是0

                try {
                    long group_id = UserSession.getSelectedGroup().getId();
                    long whiteboard_id = UserSession.getSelectedWhiteboard().getId();
                    Response response = MainServer.groupAction.remove_whiteboard(group_id, whiteboard_id);
                    ApiResultModel.parseAndCheckResponse(response, MainFrame.this, String.class, false);

                    clearWhiteboardSelection();

                    updateWhiteboardList();
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        refreshWhiteboard.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateWhiteboardList();
            }
        });
        whiteboardMenu.add(openWhiteboard);
        whiteboardMenu.add(removeWhiteboard);
        whiteboardMenu.add(refreshWhiteboard);


        JScrollPane scrollPane=new JScrollPane();    //创建滚动面板
        whiteboardList=new MyJList();

        whiteboardList.setCellRenderer(new WhiteboardListCellRenderer());
        whiteboardList.setFixedCellHeight(60);
        whiteboardList.setFont(new Font("微软雅黑", Font.TRUETYPE_FONT, 20));
        //限制只能选择一个元素
        whiteboardList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        WhiteboardListMouseListener whiteboardListMouseListener = new WhiteboardListMouseListener(whiteboardList, whiteboardMenu);
        whiteboardList.addMouseListener(whiteboardListMouseListener);
        whiteboardList.addMouseMotionListener(whiteboardListMouseListener);


        scrollPane.setViewportView(whiteboardList);    //在滚动面板中显示列表
        box.add(scrollPane);
        return box;
    }

    Box initRight(){
        Box box = Box.createVerticalBox();

        Box temp1 = Box.createHorizontalBox();
        adminLabel = new JLabel();
        addMember  = new JButton("添加成员");
        addMember.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                AddMemberDialog addMemberDialog = new AddMemberDialog(MainFrame.this);
                addMemberDialog.setVisible(true);
            }
        });
        temp1.add(adminLabel);
        temp1.add(Box.createVerticalStrut(30));
        temp1.add(addMember);
        temp1.setBorder(new EmptyBorder(8, 5, 10, 5));    //设置面板的边框
        box.add(temp1);

        JPopupMenu memberMenu = new JPopupMenu();
        JMenuItem removeMember = new JMenuItem("删除");
        JMenuItem refreshMember = new JMenuItem("刷新成员列表");
        removeMember.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int option = JOptionPane.showConfirmDialog(box,"确定要移除该成员吗？","提示",JOptionPane.YES_NO_OPTION);
                if (option == 1)
                    return;
                // 如果点了确定返回是0
                if (option == 0){
                    try {
                        long group_id = UserSession.getSelectedGroup().getId();
                        long user_id = UserSession.getSelectedMember().getId();
                        Response response =  MainServer.groupAction.remove_member(group_id, user_id);
                        ApiResultModel<List<User>> apiResult = ApiResultModel.parseAndCheckResponse(response, MainFrame.this, String.class, false);

                        clearMemberSelection();
                        updateMemberList();
                        updateWhiteboardList();

                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        });
        refreshMember.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                clearMemberSelection();
                updateMemberList();
            }
        });
        memberMenu.add(removeMember);
        memberMenu.add(refreshMember);


        JScrollPane scrollPane=new JScrollPane();    //创建滚动面板
        memberList =new MyJList();
        //限制只能选择一个元素
        memberList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        MemberListMouseListener memberListMouseListener = new MemberListMouseListener(memberList, memberMenu);
        memberList.addMouseListener(memberListMouseListener);
        memberList.addMouseMotionListener(memberListMouseListener);
        memberList.setFont(new Font("微软雅黑", Font.TRUETYPE_FONT, 12));
        scrollPane.setViewportView(memberList);    //在滚动面板中显示列表
        box.add(scrollPane);


        dismiss = new JButton("解散群组");
        dismiss.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int option = JOptionPane.showConfirmDialog(box,"确定要解散该群吗？","提示",JOptionPane.YES_NO_OPTION);
                if (option == 1)
                    return;

                try {
                    long group_id = UserSession.getSelectedGroup().getId();
                    Response response =  MainServer.groupAction.dismiss_group(group_id);
                    ApiResultModel<List<User>> apiResult = ApiResultModel.parseAndCheckResponse(response, MainFrame.this, String.class, false);

                    clearGroupSelection();
                    clearWhiteboardSelection();
                    clearMemberSelection();

                    updateGroupList();
                    updateMemberList();
                    updateWhiteboardList();


                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        });


        exit = new JButton("退出群组");
        exit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int option = JOptionPane.showConfirmDialog(box,"确定要退出群组吗？","提示",JOptionPane.YES_NO_OPTION);
                if (option == 1)
                    return;
                try {
                    long group_id = UserSession.getSelectedGroup().getId();
                    long user_id = UserSession.user.getId();
                    Response response = MainServer.groupAction.remove_member(group_id, user_id);
                    ApiResultModel<List<User>> apiResult = ApiResultModel.parseAndCheckResponse(response, MainFrame.this, String.class, false);

                    clearGroupSelection();
                    clearWhiteboardSelection();
                    clearMemberSelection();

                    updateGroupList();
                    updateMemberList();
                    updateWhiteboardList();

                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        Box temp2 = Box.createHorizontalBox();
        temp2.add(Box.createVerticalStrut(30));
        temp2.add(dismiss);
        temp2.add(exit);
        temp2.add(Box.createVerticalStrut(30));
        box.add(temp2);
        box.setPreferredSize(new Dimension(200, 960));
        return box;
    }

    public static void main(String[] args)
    {
        try {
            //解决切换输入法导致应用白屏的问题
            System.setProperty("sun.java2d.noddraw", "true");
            //使用BeautyEye开源库对整体UI进行美化
            //https://github.com/JackJiang2011/beautyeye
            org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();
            BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.translucencyAppleLike;
            UIManager.put("RootPane.setupButtonVisible", false);
            //关闭窗口在不活动时的半透明效果
            BeautyEyeLNFHelper.translucencyAtFrameInactive = false;
        } catch(Exception e) {
            e.printStackTrace();
        }
        MainFrame frame=new MainFrame();
        frame.setSize(960, 640);
        frame.setVisible(true);

    }

    @Override
    protected void initFrame() {
        setTitle("开源白板");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    //设置窗体退出时操作
        JPanel contentPane=new JPanel();    //创建内容面板
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));    //设置面板的边框
        BorderLayout borderLayout = new BorderLayout();

        contentPane.setLayout(borderLayout);
//        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.X_AXIS));
        setContentPane(contentPane);    //应用内容面板

        contentPane.add(initLeft(),BorderLayout.WEST);
        contentPane.add(initCenter(),BorderLayout.CENTER);
        contentPane.add(initRight(),BorderLayout.EAST);

        updateGroupList();
        groupList.setSelectedIndex(0);
        UserSession.setSelectedGroupIndex(0);

        updateMemberList();
        updateWhiteboardList();


        setPreferredSize(new Dimension(960, 640));
        this.setResizable(false);
        this.pack();
        //让窗口位于屏幕正中间，要放在pack()后才能生效
        this.setLocationRelativeTo(null);
    }

    @Override
    protected void initAllComponent() {

    }

    @Override
    protected void addAllComponent() {

    }
}